<%@ page language="java" contentType="text/html; charset=UTF-8"
		 pageEncoding="UTF-8"%>
<%@include file="../common/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/page.css">

	<title> <spring:message code="class.page.title"/></title>

	<script type="text/javascript">
		var _gridWidth;
		var _gridHeight;
		var parentID = -1;

		var setting = {
			check: {
				enable: true,
				chkStyle: "radio",
				radioType: "all"
			},
			data: {
				simpleData: {
					enable: true}
			},
			callback : {
				// beforeCheck : function(treeId, treeNode) {
				// 	var zTree = $.fn.zTree.getZTreeObj("FolderTreeID");
				// 	zTree.checkAllNodes(false);
				// 	return true;
				// },
				// onCheck : function(e, treeId, treeNode) {
				// 	console.log("当前被选择的节点：");
				// 	console.log(treeNode);
				// 	onCheckNode;
				// }

				onCheck : onCheckNode
		}

		};

		//页面自适应
		function resizePageSize(){
			_gridWidth = $(document).width()-12;/*  -189 是去掉左侧 菜单的宽度，   -12 是防止浏览器缩小页面 出现滚动条 恢复页面时  折行的问题 */
			_gridHeight = $(document).height()-32-80; /* -32 顶部主菜单高度，   -90 查询条件高度*/
		}

		$(function()
		{
			var dom = $("#file-add-btn-id"),
			addFileNameId = $("#add-file-name-id"),
			addFilePathId =$("#add-file-path-id"),
			allFields = $([]).add(addFileNameId).add(addFilePathId);

			resizePageSize();

			$("#file-add-btn-id").click(function (event) {
				$("#add-file-form-id").resetForm();
				$("#add-file-dialog-id").dialog('open');
			});

			$("#add-file-dialog-id").dialog({
				autoOpen : false,
				width : 400,
				height : 300,
				modal : true,
				resizable : false,
				title: "<spring:message code='file.add'/>",
				buttons: [
					{
						text: "<spring:message code='common.confirm'/>",
						click: function() {
							//点击确定后进行校验
							var bValid = true;
							allFields.removeClass( "ui-state-error" );
							bValid = bValid && checkLength( addFileNameId, 1, 256 );
							bValid = bValid && checkLength( addFilePathId, 1, 256 );
							if ( !bValid ) {
								return;
							}
							$("#add-file-form-id").submit();
						}
					},
					{
						text: "<spring:message code='common.cancel'/>",
						click: function() {
							$( this ).dialog( "close" );
						}
					}
				]
			});

			$("#add-file-form-id").ajaxForm({
				dataType: "json",
				success : function(data) {
					$("#add-file-dialog-id").dialog( "close" );
					message(data.msg);
					$("#flexiGridID").flexReload();
					reloadZtree();
				},
				error : function() {
					message("<spring:message code='common.error'/>");
				},
				complete : function(response, status) {

				}
			});

			//
			$("#new_folder_btn").click(function( event ) {
				$("#new-folder").dialog( "open" );
			});

			$("#new-folder" ).dialog({
				autoOpen : false,
				width : 400,
				modal : true,
				resizable : false,
				title: "<spring:message code='folder.name'/>",
				buttons: [
					{
						text: "<spring:message code='confirm'/>",
						click: function() {
							$.ajax({
								type : 'POST',
								url : '${pageContext.request.contextPath}/file/newFolder',
								dataType : 'json',
								cache : false,
								data : [
									{name:"parentId",value: parentID },
									{name : "folderName", value : $("#new-folder-name-id").val()}
								],
								success : function(data) {
									$('#flexiGridID').flexReload();
									$("#new-folder").dialog( "close" );
									message(data.msg);
								},
								error : function() {
									message("<spring:message code='common.error'/>");
								}
							});

						}
					},
					{
						text: "<spring:message code='common'/>",
						click: function() {
							$( this ).dialog( "close" );
						}
					}
				]
			});

			//返回上一级目录
			$("#back_btn").click(function( event ) {
				$.ajax({
					type : 'POST',
					url : '${pageContext.request.contextPath}/file/backToPardir',
					dataType : 'json',
					cache : false,
					data : [{name:"parentId",value: parentID }],
					success : function(data) {
						queryFolder(data);
					},
					error : function() {
						message("无上层目录！");
					},
				});
			});

			//copy文件
			$("#file-copy-btn-id").click(function( event ) {
				getCopyFileTreeData();
				$("#copy-file-tree-id").dialog( "open" );
			});

			$( "#copy-file-tree-id" ).dialog({
				autoOpen : false,
				width : 400,
				modal : true,
				resizable : false,
				title: "<spring:message code='file.choose.name'/>",
				buttons: [
					{
						text: "<spring:message code='confirm'/>",
						click: function() {
							var ps = [];
							var treeObj=$.fn.zTree.getZTreeObj("copyFolderTreeID");
							var	nodes=treeObj.getCheckedNodes(true);
							if(nodes && nodes.length >0) {
								for (var i = 0; i < nodes.length; i++) {
									ps[i] = nodes[i].id;
								}
							}
							var id = searchTableColumn($("#flexiGridID"),0);

							$.ajax({
								type : 'POST',
								url : '${pageContext.request.contextPath}/gdpinfo/copy',
								dataType : 'json',
								cache : false,
								data : [
									{name : "fileId", value : id},
									{name : "nodesIds", value : ps}
								],
								success : function(data) {
									$('#flexiGridID').flexReload();
									$("#copy-file-tree-id").dialog( "close" );
									message(data.msg);
								},
								error : function() {
									message("<spring:message code='common.error'/>");
								}
							});
						}
					},
					{
						text: "<spring:message code='common'/>",
						click: function() {
							$( this ).dialog( "close" );
						}
					}
				]
			});

			//移动文件   file-move-btn-id
			$("#file-move-btn-id").click(function( event ) {
				getMoveFileTreeData();
				$("#file-tree-id").dialog( "open" );

			});

			$( "#file-tree-id" ).dialog({
				autoOpen : false,
				width : 400,
				modal : true,
				resizable : false,
				title: "<spring:message code='file.choose.name'/>",
				buttons: [
					{
						text: "<spring:message code='confirm'/>",
						click: function() {
							var ps = [];
							var treeObj=$.fn.zTree.getZTreeObj("FolderTreeID");
							var	nodes=treeObj.getCheckedNodes(true);
							if(nodes && nodes.length >0) {
								for (var i = 0; i < nodes.length; i++) {
									ps[i] = nodes[i].id;
								}
							}
							var id = searchTableColumn($("#flexiGridID"),0);

							$.ajax({
								type : 'POST',
								url : '${pageContext.request.contextPath}/gdpinfo/move',
								dataType : 'json',
								cache : false,
								data : [
									{name : "fileId", value : id},
									{name : "nodesIds", value : ps}
								],
								success : function(data) {
									$('#flexiGridID').flexReload();
									$("#file-tree-id").dialog( "close" );
									message(data.msg);
								},
								error : function() {
									message("<spring:message code='common.error'/>");
								}
							});

						}
					},
					{
						text: "<spring:message code='common'/>",
						click: function() {
							$( this ).dialog( "close" );
						}
					}
				]
			});

			//重命名
			$( "#updateDailDialog" ).dialog({
				autoOpen : false,
				width : 400,
				modal : true,
				resizable : false,
				title: '文件名修改',
				buttons: [
					{
						text: "确定",
						click: function() {


							$("#updateDailFormId").submit();
						}
					},
					{
						text: "取消",
						click: function() {
							$( this ).dialog( "close" );
						}
					}
				]
			});

			$('#updateDailFormId').ajaxForm({
				dataType: "json",
				success : function(data) {
					$('#flexiGridID').flexReload();
					$("#updateDailDialog").dialog( "close" )
				},
				error : function() {
					message("<spring:message code='common.error'/>");
				},
				complete : function(response, status) {

				}
			});

			//搜索文件
			$("#query-file--btn-id").click(function( event ) {
				queryFilesByName();
				$("#flexiGridID").flexReload();
			});

			var _columnWidth= (_gridWidth-150)/4;
			$("#flexiGridID").flexigrid({
				width : _gridWidth,
				height : _gridHeight,
				<%--url : "${pageContext.request.contextPath}/file/getFileInfolist",--%>
				url : '${pageContext.request.contextPath}/file/queryFolder',
				dataType : 'json',
				colModel : [
                    {display : "<spring:message code='file.name'/>",name : 'fileName',width : _columnWidth, sortable : false,align : 'left',process: function(v,_trid,_row) {

                            var htmlContents ='';
                            if(v.substr(v.length-1,1) === "/"){
								htmlContents ='<a  id="name-row" style="color:blue;cursor:pointer;" href="#" onclick="queryFolder(\''+_row.id+'\');">';
                                htmlContents =htmlContents + '<i class="glyphicon glyphicon-folder-close" style="color: #F0DA72"></i><span style="padding-left: 10px;">';
                                htmlContents +=  v.substr(0,v.length-1) + '<span></a>';
                            }else{
								htmlContents ='<div  id="name-row" style="color:blue;" >';
                                htmlContents =htmlContents + '<i class="glyphicon glyphicon-file" style="color: #A9A9A9"></i><span style="padding-left: 10px;">';
                                htmlContents += v + '<span></div>';
								// $("#name-row").removeAttribute("href");
							}
                            return htmlContents;
                        }},

                    {display : "<spring:message code='file.content.length'/>",name : 'fileLength',width : _columnWidth, sortable : false,align : 'center',process: function(v,_trid,_row) {
                            var htmlContents = v+' kb';
                            return htmlContents;
                        }},

					{display : "<spring:message code='file.modify.time'/>",name : 'fileLastTime',width : _columnWidth, sortable : false,align : 'center'},
					{display : "<spring:message code='file.operation'/>",name : 'fileName',width : _columnWidth, sortable : true,align : 'center',process: function(v,_trid,_row)
						{
							var htmlContents1 ='<a style="color:blue;cursor:pointer;" href="${pageContext.request.contextPath}/file/download/'+_row.fileName + '" target="_blank"><i class="glyphicon  glyphicon-download-alt" title="下载"></i></a>';
							var htmlContents2 ='<a style="color:blue;cursor:pointer;" href="#" onclick="recycle(\''+_row.id+'\');"><i class="glyphicon glyphicon-trash" visited="color:purple" title="回收"></i></a>';
							var htmlContents3 ='<a style="color:blue;cursor:pointer;" href="#" onclick="shareFile(\''+_row.id+'\');"><i class="glyphicon glyphicon-share" visited="color:purple" title="分享"></i></a>';
							var htmlContents4 ='<a style="color:blue;cursor:pointer;" href="#" onclick="previewObject(\''+_row.fileName+'\');" ><i class="glyphicon glyphicon-eye-open" title="预览"></i></a>';
							return htmlContents1 + "   " + htmlContents2 + "    " + htmlContents3+"   "+ htmlContents4;
						}}

				],
				resizable : false, //resizable table是否可伸缩
				useRp : true,
				usepager : false, //是否分页
				autoload : false, //自动加载，即第一次发起ajax请求
				hideOnSubmit : true, //是否在回调时显示遮盖
				showcheckbox : true, //是否显示多选框
				rowbinddata : true,
				rowhandler : rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
				numCheckBoxTitle : "<spring:message code='common.selectall'/>"
			});

			query([
				{name:"parentID",value:parentID}
			]);
        });

		function getMoveFileTreeData() {
			$.ajax({
				type : 'POST',
				url : '${pageContext.request.contextPath}/gdpinfo/queryFileInfoZtreeList',
				dataType : 'json',
				cache : false,
				data : [],
				success : function(data) {
					$.fn.zTree.init($("#FolderTreeID"), setting, data);
				},
				error : function() {
					message("<spring:message code='common.error'/>");
				}
			});
		}

		function getCopyFileTreeData() {

			var settingBond = {
				check: {
					enable: true,
					chkStyle: "radio",
					radioType: "all"
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback : {
					onCheck : onCheckNode
				}
			};

			$.ajax({
				type : 'POST',
				url : '${pageContext.request.contextPath}/gdpinfo/queryFileInfoZtreeList',
				dataType : 'json',
				cache : false,
				data : [],
				success : function(data) {
					$.fn.zTree.init($("#copyFolderTreeID"), settingBond, data);
				},
				error : function() {
					message("<spring:message code='common.error'/>");
				}
			});
		}

		function queryFolder(parent_id) {
			parentID = parent_id;
			query([
				{name:"parentID",value:parent_id}
			]);
			$("#flexiGridID").flexReload();
		}

		function queryFilesByName() {
			query([
				{name:"fileNames",value:$("#file-name-input-id").val()}
			]);
			$("#flexiGridID").flexReload();
		}

		function recycle(id) {
			console.log("id="+id);
			console.log();
			$.ajax({
				type : 'POST',
				url : '${pageContext.request.contextPath}/file/recycle/'+id+'',
				dataType : 'json',
				cache : false,
				data : {},
				success : function() {
					message("回收成功！");
					$("#flexiGridID").flexReload();
				},
				error : function() {
					message("<spring:message code='common.error'/>");
				},
			});
		}

		function shareFile(id) {
			console.log("id="+id);
			console.log();
			$.ajax({
				type : 'POST',
				url : '${pageContext.request.contextPath}/file/shareFile/'+id+'',
				dataType : 'json',
				cache : false,
				data : {},
				success : function() {
					 message("分享成功！")
					$("#flexiGridID").flexReload();
				},
				error : function() {
					message("<spring:message code='common.error'/>");
				},
			});
		}

        function query(param1){
            $('#flexiGridID').flexOptions({
                newp: 1,
                extParam: param1||[]
            }).flexReload();
        };

		//将节点保存到数据库
		function onCheckNode(event, treeId, treeNode) {
			console.info(treeNode.id);
		}

		function rowDbclick(r){
			$(r).dblclick(
					function() {
						var columnsArray = $(r).attr('ch').split("_FG$SP_");
						$("#rename-old-file-name-id").val(columnsArray[3]);
						$("#rename-new-file-name-id").val(columnsArray[3]);
						$("#updateDailDialog").dialog("open");
					});
		}

		function previewObject(objectKey) {
			console.log("[Liu Debug]预览文件~previewObject:objectKey="+objectKey);
			console.log();
			$.ajax({
				type : 'POST',
				url : '${pageContext.request.contextPath}/file/preview/'+objectKey+'',
				dataType : 'json',
				cache : false,
				data : {},
				success : function(data) {
					console.log("[Liu Debug]预览文件~previewObject:objectKey="+objectKey);
					initPreviewWindow(data.id,data.msg);
					setCurrentPreviewMode(judgeFileTypeBySuffix(getFileSuffix(objectKey)),data.tempUrl);
					openPreview();//打开预览窗口

					$("#flexiGridID").flexReload();
				},
				error : function() {
					message("<spring:message code='common.error'/>");
				},

			});
		}

		//[Liu]初始化预览窗口
		function initPreviewWindow(key,msg) {
			$("#previewInfo").html("文件ID："+key+"+文件信息："+msg);
		}

		//[Liu]隐藏所有的预览Div
		function hideAllPreviewDiv() {
			document.getElementById("previewImage").style.display="none";
			document.getElementById("previewAudio").style.display="none";
			document.getElementById("previewVideo").style.display="none";
			document.getElementById("previewDoc").style.display="none";
			document.getElementById("previewUnknown").style.display="none";
		}

		//[Liu]选择正确的预览模式
		function setCurrentPreviewMode(type,path) {
			hideAllPreviewDiv();
			switch (type) {
				case "img":
					$('#previewImage').css("display","block");
					$('#preImageSrc').attr("src",path)
					break;
				case "audio":
					$('#previewAudio').css("display","block");
					$('#preAudioSrc').attr("src",path)
					break;
				case "video":
					$('#previewVideo').css("display","block");
					$('#preVideoSrc').attr("src",path)
					break;
				case "office":
					$('#preDocSrc').attr("src","https://view.officeapps.live.com/op/view.aspx?src="+path);
					$('#previewDoc').css("display","block");
					break;
				case "unknown":
					$('#previewUnknown').css("display","block");
					break;
				default:

			}
		}

		//[Liu]获取后缀
		function getFileSuffix(path) {
			var index= path.lastIndexOf(".");
			var suffix = path.substr(index+1);
			console.log("获取后缀~getFileSuffix:path="+path);
			console.log("获取后缀~getFileSuffix:suffix="+suffix);
			return suffix;
		}

		//[Liu]判断文件类型
		function judgeFileTypeBySuffix(suffix) {
			let result = "unknown";
			let imgType = ["jpg","jpeg","bmp","png"];
			let audioType = ["mp3","wav","ogg"]
			let videoType = ["mp4","ogg"];
			let officeType = ["doc","docx","ppt","pptx","xsl","xslx","txt"];
			if(imgType.indexOf(suffix.toLowerCase()) !== -1)
				result = "img";
			if(audioType.indexOf(suffix.toLowerCase()) !== -1)
				result = "audio";
			if(videoType.indexOf(suffix.toLowerCase()) !== -1)
				result = "video";
			if(officeType.indexOf(suffix.toLowerCase()) !== -1)
				result = "office";
			console.log("[Liu Debug]判断类型~judgeFileTypeBySuffix:结果="+result);
			return result;
		}

		//[Liu]通过改变Style隐藏预览窗口并停止所有播放
		function closePreview() {
			$("#preAudioSrc")[0].pause();//暂停音乐
			$('#preVideoSrc').get(0).pause();//暂停视频
			//$('video').trigger('pause'); //关闭所有的视频播放
			const preDiv = document.getElementById("previewWindow");
			preDiv.style.display="none";
		}

		//[Liu]通过改变Style展现预览窗口
		function openPreview() {
			const preDiv = document.getElementById("previewWindow");
			preDiv.style.display="block";
		}
	</script>

	<style type="text/css">
		.navbar-nav>li>a {
			line-height: 10px;
			font-size: 14px;
			font-weight: 700;
			padding-top: 13px;
		}
	</style>
</head>
<body style="display: flex;flex-direction: column">

	<nav  class="navbar-collapse collapse">
		<ul class="nav navbar-nav fa-ul">

			<li>
				<input id="file-name-input-id" class="btn btn-default btn-sm" >
				</input>
			</li>
			<li>
				<a id="query-file--btn-id" href="#" class="btn btn-default btn-sm">
					<span><spring:message code="file.query"></spring:message> </span>
				</a>
			</li>
			<li>
				<a id="file-add-btn-id" href="#" class="btn btn-default btn-sm">
					<i class="glyphicon glyphicon-plus-sign"></i>
					<span><spring:message code="file.add"></spring:message> </span>
				</a>
			</li>
			<li>
				<a id="new_folder_btn" href="#" class="btn btn-default btn-sm">
					<i class="glyphicon glyphicon-folder-open"></i>
					<span><spring:message code="file.addfolder"></spring:message> </span>
				</a>
			</li>
			<li>
				<a id="back_btn" href="#" class="btn btn-default btn-sm">
					<i class="glyphicon glyphicon-share-alt"></i>
					<span><spring:message code="back_up"></spring:message> </span>
				</a>
			</li>
			<li>
				<a id="file-copy-btn-id" href="#" class="btn btn-default btn-sm">
					<i class="glyphicon glyphicon-duplicate"></i>
					<span><spring:message code="file.copy"></spring:message> </span>
				</a>
			</li>
			<li>
				<a id="file-move-btn-id" href="#" class="btn btn-default btn-sm">
					<i class="glyphicon glyphicon-log-out"></i>
					<span><spring:message code="file.move"></spring:message> </span>
				</a>
			</li>

		</ul>
	</nav>

	<table id="flexiGridID" style="display: block;margin: 0px;">

	</table>

	<div id="add-file-dialog-id" style="display: none">
		<form id="add-file-form-id" action="${pageContext.request.contextPath}/file/addFile"  method="post" enctype="application/x-www-form-urlencoded">
			<div class="form-group">
				<span for="add-file-name-id"><spring:message code="file.name"></spring:message> </span>
				<input class="form-control" type="text" name="fileName" id="add-file-name-id">
			</div>
			<div class="form-group">
				<span for="add-file-path-id"><spring:message code="file.choose.name"></spring:message> </span>
				<input class="form-control" type="file" name="filePath" id="add-file-path-id">
			</div>
		</form>
	</div>

	<div id="share-tips-diags-id" style="display: none">
	   <textarea id="share-tips-id" rows="4" cols="10" style="width: 367px;height: 134px">

	   </textarea>

	</div>


	<div id="previewWindow" style="
       display: none;
      background-color: rgb(255,255,255);
      /*border:1px solid #000;*/
      position: absolute;
      margin: auto;
      top: 0;bottom: 0;left: 0;right: 0;
      resizable : true;
      width: 640px;height: 440px;
      z-index: 99999;
      /*效果*/
      border-radius: 5px;
      box-shadow: 3px 3px  10px rgb(112,168,211);">
		<div id="previewInfo" style="height: 20px;background-color: rgb(112,168,211);text-align: center;line-height: 20px">
		</div>

		<div id="previewImage" align="center">
			<p>图片</p>
			<img id="preImageSrc" src="" controls="controls" style="background-position: center center;
       			 background-size: contain;
       			 object-fit: contain;max-width: 640px;max-height: 380px;"
				 frameborder='1'>
		</div>

		<div id="previewVideo" align="center">
			<p>视频</p>
			<div id="videoDiv" controls="controls" style="background-position: center center;
					background-size: contain;
					object-fit: contain;width: 640px;height: 380px;">
				<video id="preVideoSrc" src="" controls="controls" style="max-width: 100%;height:100%;">您的浏览器不支持 video 标签。</video>
			</div>
		</div>

		<div id="previewAudio" style="" align="center">
			<p>音频</p>
			<div id="audioDiv" style="margin:0 auto;
        			 display:table;">
				<audio id="preAudioSrc" controls>
					您的浏览器不支持 audio 元素。
				</audio>
			</div>
		</div>

		<div id="previewDoc" align="center" style="width: 100%;height: 85%;">
			<p>文档</p>
			<iframe id="preDocSrc" src="" width='100%' height='100%' frameborder='1'>
			</iframe>
		</div>

		<div id="previewUnknown" align="center">
			<font size="5">不支持的文件！</font>
		</div>

		<div id="previewButton"
			   style="bottom: 0;
			   height: auto;width: auto;
			   cursor: pointer;
			   font-family: Microsoft YaHei; /* 设置字体 */
			   float: left;
			   position: absolute">
			<button onclick="closePreview()" style="background: #d5effc;color: #d70000">关闭预览</button>
		</div>
	</div>


	<!-- 新建文件夹   目录树 -->
	<div id="new-folder" class="zTreeDemoBackground left"
		 title="<spring:message code="folder.name"/>"  align="center"
		 style="display: none;">
		<input class="form-control" type="text" name="folderName" id="new-folder-name-id">
	</div>

	<!-- 新建文件   目录树 -->
	<div id="file-tree-id" class="zTreeDemoBackground left"
		 title="<spring:message code="file.choose.name"/>"  align="center"
		 style="display: none;">
		<ul id="FolderTreeID" class="ztree"></ul>
	</div>

	<%--重命名	--%>
	<div id="updateDailDialog" style="display: none;">
		<form id="updateDailFormId" action="${pageContext.request.contextPath}/file/updateName" method="post" >
			<input type="hidden" id="rename-old-file-name-id" name="oldFileName" />
			<!-- hidden -->
			<table class="table table-hover">
				<tr>
					<td class="fileName">
						<label><spring:message code='file.rename'/></label>
					</td>
					<td class="fileValue" >
						<input type="text" id="rename-new-file-name-id" name="newFileName" />
						<span class="mand">*</span>
					</td>
				</tr>

			</table>
		</form>
	</div>

	<div id="copy-file-tree-id" class="zTreeDemoBackground left"
		 title="<spring:message code="file.choose.name"/>"  align="center"
		 style="display: none;">
		<ul id="copyFolderTreeID" class="ztree"></ul>
	</div>
</body>
</html>